﻿using EasySchedule.DataModel;
using EasySchedule.ServiceAgent;
using Microsoft.Practices.Prism.StoreApps;
using Microsoft.Practices.Prism.StoreApps.Interfaces;
using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Windows.Input;
using Windows.Storage;

namespace EasySchedule.ViewModels
{
    public class PollViewModel : ViewModelBase
    {
        private string description;
        private Poll details;
        private string id;
        private ApplicationDataContainer localSettings;
        private ServiceManager manager;
        private ObservableCollection<string> options;
        private ObservableCollection<ParticipantViewModel> participants;
        private Poll poll;
        private string pollFileName;
        private string pollKey;
        private ObservableCollection<DateTime> selectedDates;
        private ServiceGateway<Poll> serviceGateway;

        private ISessionStateService session;
        private StatesType state;
        private string title;
        private string nrParticipants;
        public PollViewModel(UserTypePoll userPoll, ISessionStateService session)
        {
            localSettings = ApplicationData.Current.LocalSettings;
            localSettings.CreateContainer(serviceDataKey, ApplicationDataCreateDisposition.Always);

            var access_token = localSettings.Containers[settingsKey].Values["access_token"] as string;
            var access_token_secret = localSettings.Containers[settingsKey].Values["access_token_secret"] as string;

            this.session = session;

            if (string.IsNullOrEmpty(access_token) || string.IsNullOrEmpty(access_token_secret))
            {
                //TODO: Validate if this should be here !
                this.manager = new ServiceManager();
            }
            else
            {
                this.manager = new ServiceManager(access_token, access_token_secret);
                this.serviceGateway = new ServiceGateway<Poll>(this.manager);
            }

            this.LoadCommand = new DelegateCommand<bool>(ExecuteLoad, CanExecuteLoad);

            this.Title = userPoll.title;
            this.id = userPoll.pollId;
            this.State = userPoll.state;
            this.pollKey = "poll" + this.id;
            this.pollFileName = string.Format("poll{0}.xml", this.id);
            this.NrParticipants = userPoll.nrOfParticipants;
        }

        public string Description
        {
            get { return description; }
            set { SetProperty(ref description, value); }
        }

        public ICommand LoadCommand { get; private set; }

        public string NrParticipants
        {
            get { return nrParticipants; }
            set { SetProperty(ref nrParticipants, value); }
        }

        public ObservableCollection<string> Options
        {
            get { return options; }
            set { SetProperty(ref options, value); }
        }

        public ObservableCollection<ParticipantViewModel> Participants
        {
            get { return participants; }
            set { SetProperty(ref participants, value); }
        }

        public ObservableCollection<DateTime> SelectedDates
        {
            get { return selectedDates; }
            set { SetProperty(ref selectedDates, value); }
        }

        public StatesType State
        {
            get { return state; }
            set { SetProperty(ref state, value); }
        }

        public string Title
        {
            get { return title; }
            set { SetProperty(ref title, value); }
        }
        private bool CanExecuteLoad(bool forceRefresh)
        {
            if (string.IsNullOrEmpty(this.id))
                return false;
            return true;
        }

        private async void ExecuteLoad(bool forceRefresh)
        {
            if (forceRefresh)
            {
                this.poll = await this.serviceGateway.GetModelData(OAuthConstants.URL_POLL + this.id, pollFileName);
            }
            else
            {
                if (this.session.SessionState.ContainsKey(pollKey))
                {
                    this.poll = this.session.SessionState[pollKey] as Poll;
                }
                else
                {
                    try
                    {
                        this.poll = await this.serviceGateway.GetModelData(pollFileName);
                    }
                    catch (FileNotFoundException)
                    {
                        if (this.LoadCommand.CanExecute(true)) this.LoadCommand.Execute(true);
                    }
                }
            }
            if (this.poll == null) return;
            this.session.SessionState[pollKey] = this.poll;

            this.Description = this.poll.description;
            this.Options = new ObservableCollection<string>();
            
            foreach (var option in this.poll.options)
            {
                string optionValue = string.Format("{0} \n {1}",
                        option.date.ToString("d MMMM", CultureInfo.CurrentCulture),
                        option.date.ToString("hh:mm:ss", CultureInfo.CurrentCulture));
                if (option.dateSpecified)
                    this.Options.Add(optionValue);
                if (option.dateTimeSpecified)
                    this.Options.Add(optionValue);
                if (option.finalSpecified)
                    this.Options.Add(option.Value);
            }
            this.Participants = new ObservableCollection<ParticipantViewModel>();
            foreach (var participant in this.poll.participants.participant)
            {
                if (participant != null)
                    this.Participants.Add(new ParticipantViewModel(participant));
            }
        }
    }
}